/**
 * Created by wwh on 2017/7/20.
 */
/**
 * 时间格式取年月日
 * @param time
 * @returns {*}
 */
function getYearMonthDate(time) {
    if(time!=null) {
        var YMD = time.split(" ")[0];  // 年月日
        var HMS = time.split(" ")[1];  // 时分秒
        return YMD;
    }
    return null;
}

layui.config({
    base: '../../static/js/layuiModulesEX/'
});
layui.use(['paging', 'laytpl','form','laydate','upload'], function() {
    var $ = layui.jquery,
        paging = layui.paging(),
        layerTips = parent.layer === undefined ? layui.layer : parent.layer, //获取父窗口的layer对象
        layer = layui.layer, //获取当前窗口的layer对象
        laytpl = layui.laytpl,
        laydate = layui.laydate,
        image ={},
        form = layui.form();

    var vm = new Vue({
        el:'#Vue',
        data:{
            show:true,
            addInfo:false,
            editInfo:false,
            internInfoDetail:{},
            studentInfo: {
                id: "",
                userid: userid
            },
            internInfo:{},
            orgInfo:{
            },
            user:{
                id:userid
            }
        },
        methods:{
            /**
             * 添加按钮
             */
            add:function () {
                if(vm.studentInfo.advisestate==0){
                    layer.msg('请先申请实习指导老师');
                }
                else if(vm.studentInfo.advisestate==1){
                    layer.msg('请等待导师接收申请');
                }
                else if(vm.studentInfo.advisestate==2) {
                    axios.get('/internInfo/findIsUnderReview/'+userid)
                        .then(function (response) {
                            console.log(response.data);
                            if(response.data.flag != 1){
                                vm.internInfo = {sno: vm.studentInfo.id};
                                $('select[name=org]').next().find('[lay-value="0"]').click()
                                $('select[name=orgattr]').next().find('[lay-value="0"]').click()
                                $('#workpic').attr('src', "");
                                $('#span').show();
                                vm.show = false;
                                vm.isAdd = true;
                                vm.addInfo = true;
                            }
                            else{
                                layer.msg("当前已存在处于审核中的记录");
                            }
                        })
                        .catch(function (msg) {
                            console.log(msg);
                        })

                }
                else if(vm.studentInfo.advisestate==3){
                    layer.msg('您已被无情拒绝，请重新申请指导教师');
                }
            },
            /**
             * 申请实习指导教师按钮
             */
            addTeacher:function () {
                $.get('/student/addTeacher?schoolId='+vm.studentInfo.schoolid+
                    '&teacherType=2',null,function (html) {
                    layer.open({
                        type:1,
                        title:"选择指导老师",
                        area:['600px','300px'],
                        content:html,
                        success: function (layero,index) {
                            // 监听教师
                            form.on('submit(saveTeacher)',function () {
                                vm.studentInfo.internadvisor = $("#chooseTeacher").val();
                                vm.studentInfo.advisestate = 1;
                                vm.studentInfo.state = 1;
                                $.ajax({
                                    type: "POST"
                                    , url: "/student/modify"
                                    , dataType: "json"
                                    , contentType: "application/json"
                                    , data: JSON.stringify(vm.studentInfo)
                                    , success: function (response) {
                                        console.log(response.data);
                                        layer.msg('保存成功',{icon:1,time:1500},function () {
                                            layer.close(index);
                                        });
                                    }
                                    , error: function (msg) {
                                        layer.msg('保存教师信息失败', {icon: 2, time: 1000});
                                        console.log(msg);
                                    }
                                });
                                return false;
                            });
                            return false;
                        },
                        end:function (index) {
                            layer.close(index);
                        }
                    })
                });
            },
            /**
             * 返回按钮
             */
            reload:function () {
                paging.init();
                vm.addInfo = false;
                vm.editInfo = false;
                vm.show = true;
            },
            /**
             * 保存数据(暂时保存与提交审核)
             */
            save:function () {
                // 对下拉框时间框的数据绑定有问题
                vm.internInfo.orgid = $("#org option:selected").val();
                vm.internInfo.start = $("#start").val();
                vm.internInfo.end = $("#end").val();
                vm.internInfo.sno = vm.studentInfo.id;
                vm.internInfo.orgattr = 3;
                vm.internInfo.auditsug = '暂无';
                console.log(vm.internInfo);
                // console.log(vm.studentInfo);

                var url_internInfo = vm.internInfo.id == null ? "/internInfo/add":"/internInfo/modify";
                var url_studentInfo = "/student/modifyOneById";
                axios.all([axios.post(url_internInfo,vm.internInfo),axios.post(url_studentInfo,vm.studentInfo)])
                    .then(function (res) {
                        var res_internInfo = res[0];
                        var res_studentInfo = res[1];
                        // console.log(res_internInfo);
                        // console.log(res_studentInfo);
                        if(res_internInfo.data.success&&res_studentInfo.data.success){
                            layer.msg("保存成功",{icon:1,time:1500},function () {
                               vm.reload();
                            });
                        }
                    })
                    .catch(function (msg_internInfo,msg_studentInfo) {
                        console.log(msg_internInfo);
                        console.log(msg_studentInfo);
                    });

            }
        }
    });

    // 根据userid获得studentInfo中的sno
    axios.get("/student/findDetail/"+userid)
        .then(function (response) {
            // console.log(response.data);
            vm.studentInfo = response.data.data.studentInfo;
            vm.internInfo.sno = response.data.data.studentInfo.id;
            // console.log(vm.studentInfo);
            // if(vm.studentInfo.advisestate==0||vm.studentInfo.advisestate==3){
            //     var html = "<a href='javascript:;' class='layui-btn layui-btn-small' @click='addTeacher' id='addTeacher'><i class='layui-icon'>&#xe608;</i> 申请实习指导老师 </a>";
            //     $('#start_button').append(html);
            // }
        })
        .catch(function (response) {
            console.log(response);
        });

    paging.init({
        url: '/internInfo/findBatchByUserId', //地址
        elem: '#content', //内容容器
        params: { //发送到服务端的参数
            id:userid
        },
        contentType : "application/json; charset=utf-8",
        type: 'POST',
        tempElem: '#tpl', //模块容器
        pageConfig: { //分页参数配置
            elem: 'paged', //分页容器
            pageSize:10 //分页大小
        },
        success: function() { //渲染成功的回调
            // alert('渲染成功');
        },
        fail: function(msg) { //获取数据失败的回调
            // alert('获取数据失败')
        },
        complate: function() { //完成的回调
            // alert('处理完成');
            /**
             *绑定按钮
             */
            $('#content').children('tr').each(function () {
                //获取每行记录id值
                var $that = $(this).children('td:last-child');
                var id = $that.children('a[data-opt=details]').data('id');
                // console.log(id);
                /**
                 * 预览按钮
                 */
                $that.children('a[data-opt=details]').on('click', function () {
                    axios.get('/internInfo/findOne/' + id)
                        .then(function (response) {
                            console.log(response.data);
                            $('#workpic').attr('src',"");
                            vm.internInfoDetail=response.data;
                            // console.log(vm.internInfoDetail);

                            layer.open({
                                type: 1,
                                title: "实习信息",
                                content: laytpl($('#detailTpl').html()).render(vm.internInfoDetail),
                                shade: [0.5, '#FFF'], //模态框
                                area: ['700px', '600px'],
                                zIndex: 19950924,
                                btn: ['返回'],
                                yes: function (index) {
                                    layer.close(index);
                                }
                            });
                            //改变图片显示 Todo 营业执照显示问题
                            if (response.data.data.image !== null) {
                                console.log(response.data.data.image);
                                $('#picture').attr('src', response.data.data.image.path);
                            }
                        })
                        .catch(function (response) {
                            console.log(response);
                        });
                });

                /**
                 * 编辑按钮
                 */
                $that.children('a[data-opt=edit]').on('click',function () {
                    $('#span').hide();
                    $('#workpic').attr('src',null);// 清空脏数据
                    axios.get('/internInfo/findOne/' + id)
                        .then(function (response) {
                            $('#workpic').attr('src',"");
                            //改变图片显示 Todo 营业执照显示问题
                            if (response.data.data.image !== null) {
                                console.log(response.data.data.image);
                                $('#workpic').attr('src', response.data.data.image.path);
                            }
                            vm.internInfo = response.data.data.internInfo;
                            vm.orgInfo = response.data.data.orgInfo;
                            console.log(vm.internInfo);
                            console.log($('select[name=org]'));
                            $('select[name=org]').next().find('[lay-value="'+ vm.internInfo.orgid +'"]').click()
                            vm.show = false;
                            vm.editInfo = true;
                        })
                        .catch(function (response) {
                            console.log(response);
                        });
                });
            });
        }
    });

    //上传照片
    layui.upload({
        url: '/upload/workingpic',
        elem: '#workEnvironment',
        success: function (response) {
            // console.log(response);
            image.path = response.data;
            image.description = "工作环境";
            image.isencrypted = 2;//不需要加密
            console.log(image);
            axios.post("/image/add", image)
                .then(function (response) {
                    console.log(response);
                    axios.get("/image/find/" + response.data.data)
                        .then(function (response) {
                            console.log(response);
                            $('#workpic').attr('src', response.data.data);
                        })
                        .catch(function (response) {
                            console.log(response);
                        });
                })
                .catch(function (response) {
                    console.log(response);
                });
        },
        before: function () {
            console.log('outsidepic文件上传中');
        }
    });

    //上传pdf
    layui.upload({
        url: '/upload/contract',
        title: '请上传pdf',
        ext:"pdf",
        elem: '#contract',
        success: function (response) {
            $('#workpic').attr('src', response.data);
            console.log(response.data);
            image.path = response.data;
            image.description = "工作环境";
            image.isencrypted = 2;//不需要加密
            axios.post("/image/add", image)
                .then(function (response) {
                    vm.internInfo.workingpic = response.data.data;
                    console.log(vm.internInfo);
                })
                .catch(function (response) {
                    console.log(response);
                });
        },
        before: function () {
            console.log('contractPDF上传中');
        }
    });



    form.on('select(orgattr)', function (data) {
        vm.internInfo.orgattr = data.value;
    });

    // 监听radio
    form.on('radio(orgattr)',function (data) {
        // console.log(data.value);
        vm.internInfo.orgattr =data.value;
    });

    // 监听审核提交与必选项
    form.on('submit(submit)',function () {
        vm.internInfo.state = "2";   // 提交审核状态变为待审核
        if(vm.studentInfo.state==1){
            vm.studentInfo.state=2;
        }
        else if(vm.studentInfo.state == 3){
            vm.studentInfo.state = 4;
        }
        if($('#org').val()==null){
            layer.msg('请选择单位！',{icon:0,time:1000});
        }
        else{
            // console.log(vm.internInfo);
            vm.save();
        }
    });

    // 监听暂时保存
    form.on('submit(saveTemporary)',function () {
        vm.internInfo.state = "1";   // 提交审核状态变为未申请
        if($('#org').val()==null){
            layer.msg('请选择单位！',{icon:0,time:1000});
        }
        else{
            vm.save();
        }
    });
});